/*
 * DCE400服务系统 -- 后端服务接口 -- 数据访问层 -- 工单数据访问
 * 包括：
 */
package dao

import (
	"errors"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server/app/entity"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server/app/global"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/db"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/util"
	"go.uber.org/zap"
	"strings"
	"time"
)

//********************************************
//Func  ：查询数据库：工单列表分页查询。
//Method：startDate 格式 yyyy-mm-dd hh:MM:dd
//Usage ：
//********************************************
func QueryWorkOrderList(page, pageSize int, mobile, startDate, endDate string) (int64, []*entity.WorkOrder, error) {
	offset := (page - 1) * pageSize
	session := db.Session().Table("work_order") //工单
	defer session.Close()

	if mobile != "" { //根据mobile查找所属工单，未指明就全部输出
		session = session.Where("customer_mobile=?", mobile)
	}
	if pageSize > 0 {
		session.Limit(pageSize, offset)
	}

	if startDate != "" {
		dtLayout := "2006-01-02 15:04:05" //严格按照time包要求的格式
		loc := db.TZLocation()            //转换日期的时区
		_, serr := time.ParseInLocation(dtLayout, startDate, loc)
		if serr == nil {
			session = session.And("start_at >= ?", startDate)
		}
	}
	if endDate != "" {
		dtLayout := "2006-01-02 15:04:05" //严格按照time包要求的格式
		loc := db.TZLocation()            //转换日期的时区
		_, eerr := time.ParseInLocation(dtLayout, endDate, loc)
		if eerr == nil {
			session = session.And("end_at <= ?", endDate)
		}
	}

	orders := []*entity.WorkOrder{}
	total, err := session.FindAndCount(&orders)
	if err != nil {
		return 0, nil, err
	}
	return total, orders, nil
}

//********************************************
//Func  ：查询数据库：指定工单的详情
//Method：GET
//Usage ：
//********************************************
func QueryWorkOrderDetail(Id int64) (*entity.WorkOrder, error) {
	session := db.Session().Table("work_order") //.Where("id=?",operatorId).Get(&operator)
	defer session.Close()

	var workOrder entity.WorkOrder
	has, err := session.Where("id=?", Id).Get(&workOrder)
	if err != nil || has == false {
		return nil, err
	}
	return &workOrder, nil
}

//********************************************
//Func  ：添加新工单
//Method：POST
//Usage ：
//********************************************
func InsertWorkOrder(workorder entity.WorkOrder) (*entity.WorkOrder, error) {
	var err error
	if len(strings.TrimSpace(workorder.Title)) <= 0 { //姓名（必填）/单位名称
		return nil, errors.New("title is none")
	}

	if len(strings.TrimSpace(workorder.Body)) <= 0 {
		return nil, errors.New("mobile is none")
	}

	workorder.CreatedAt = time.Now()
	workorder.Status = 0
	workorder.Id = util.GenSnowflakeInt64()
	global.Log.Info("InsertWorkOrder: ", zap.Any("work_order:", workorder))

	session := db.Session().Table("work_order")
	defer session.Close()
	err = session.Begin()
	if err != nil {
		return nil, errors.New("db session begin failed.")
	}

	_, err = session.Insert(&workorder) //插入
	if err != nil {
		session.Rollback()
		return nil, err
	}
	err = session.Commit()
	if err != nil {
		return nil, err
	}

	/*	var newer entity.WorkOrder
		db.Session().Table("work_order").
			Where("id =?", workorder.Id).
			Desc("id").Get(&newer)
	*/
	return &workorder, nil
}

func MarkLabelToWorkOrder(labelId, workOrderId int64) (*entity.WorkOrder, error) {

	var err error
	if workOrderId <= 0 {
		return nil, errors.New("work order id is none")
	}

	session := db.Session().Table("work_order")
	defer session.Close()

	err = session.Begin()
	if err != nil {
		return nil, err
	}
	var order entity.WorkOrder
	_, err = session.Where("id=?", workOrderId).
		Cols("label_ids").
		Update(&entity.WorkOrder{})

	if err != nil {
		session.Rollback()
		return nil, err
	}
	err = session.Commit()
	return &order, err
}

//********************************************
//Func  ：更新工单信息
//Method：POST
//Usage ：
//********************************************
func UpdateWorkOrder(workorder entity.WorkOrder, cols string) error {
	var err error
	if workorder.Id <= 0 {
		return errors.New("work order id is none")
	}
	session := db.Session().Table("work_order")
	defer session.Close()

	err = session.Begin()
	if err != nil {
		return err
	}
	workorder.FinishAt = time.Now()

	if cols == "" {
		cols = "status,reply,finish_at,cur_process_id" //如果有输入的cols项，优先使用。如没有，用默认的
	}

	_, err = session.Where("id=?", workorder.Id).
		Cols(cols).Update(workorder)
	if err != nil {
		return err
	}

	err = session.Commit()
	return err

}

//********************************************
//Func  ：Customer删除
//Method：DELETE
//Usage ：客户-账号删除--物理删
//********************************************
func DeleteWorkOrder(workerOrderId int64) error {
	if workerOrderId <= 0 {
		return errors.New("work order id is none")
	}

	session := db.Session().Table("work_order")
	defer session.Close()
	session.Begin()

	cnt, err := session.Where("id=?", workerOrderId).Delete(&entity.WorkOrder{})
	if err != nil {
		session.Rollback()
		return err
	}
	if cnt <= 0 {
		session.Rollback()
		return errors.New("remove 0 order")
	}
	err = session.Commit()
	return err
}
